package com.lwb.ztx.lives.widget;

import android.animation.ValueAnimator;
import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.media.AudioManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.WindowManager;
import android.widget.CheckBox;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import com.lwb.ztx.R;
import com.lwb.ztx.bean.LiveBean;
import com.lwb.ztx.database.GreenDaoManager;
import com.lwb.ztx.database.greendao.dao.LiveDao;
import com.lwb.ztx.database.greendao.db.Live;
import com.lwb.ztx.lives.view.LiveSizePopupMenu;
import com.lwb.ztx.lives.view.ijkplayer.Settings;
import com.lwb.ztx.lives.view.ijkplayer.media.IjkVideoView;
import com.lwb.ztx.utils.CommonUtil;
import com.lwb.ztx.utils.ListUtils;
import com.lwb.ztx.utils.LogUtils;
import com.lwb.ztx.utils.ToolsUtil;

import org.w3c.dom.Text;

import java.util.List;

import me.imid.swipebacklayout.lib.app.SwipeBackActivity;
import tv.danmaku.ijk.media.player.IMediaPlayer;
import tv.danmaku.ijk.media.player.IjkMediaPlayer;

public class LivePlayActivity extends SwipeBackActivity implements View.OnClickListener, RadioGroup.OnCheckedChangeListener, LiveLandChannelAdapter.OnChannelItemClickListener {
    public static List<LiveBean> allLives;
    public static int index;
    public static final String url_3 = "http://106.36.45.36";
    public static final String url_1 = "http://61.129.131.52";
    public static final String url_2 = "http://115.233.62.23";

    public static String current_url = url_1;

    private LinearLayout lySystemParent;
    private IjkVideoView videoView;
    private RelativeLayout flVideoView;
    private RelativeLayout rlLoadView;
    private TextView tvLoadmsg;
    private ImageView ivFullScreen;

    private String path = "";
    private Settings mSettings;
    private String title = "";
    private boolean mBackPressed;
    private int count = 0;

    private final int CONNECTION_TIMES = 5;


    private TextView tvTitle;
    private ImageView ivBack;
    private ImageView ivMenu;
    private LinearLayout lyFloor;
    private View vClose;

    private static int SIZE_DEFAULT = 0;
    private static int SIZE_4_3 = 1;
    private static int SIZE_16_9 = 2;
    private int currentSize = SIZE_16_9;


    private int screenWidth = 0;
    private int screenHeight = 0;
    private boolean isShowToolbar = true;

    private LiveSizePopupMenu popupMenu;

    private ImageView lastChannel;
    private ImageView nextChannel;
    private TextView indexChannel;

    private RadioGroup radioGroup;

    private CheckBox liveCollect;

    private LiveDao dao;
    private AudioManager audio;
    private SeekBar seekBar;
    private int currentVolume;

    private View landBtnView;
    private View landLastBtn;
    private View landNextBtn;
    private View selectChannelBtn;

    private RecyclerView channelList;
    private LiveLandChannelAdapter channelListAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_live);
        dao = GreenDaoManager.getDaoSession(this).getLiveDao();
        audio = (AudioManager) getSystemService(Service.AUDIO_SERVICE);
        seekBar = (SeekBar) this.findViewById(R.id.live_sound);
        currentVolume = audio.getStreamVolume(AudioManager.STREAM_MUSIC);  //获取当前值
        seekBar.setProgress(currentVolume);
        path = getIntent().getStringExtra("url");
        if (path == null || "".equals(path)) {
            path = "http://106.36.45.36/live.aishang.ctlcdn" +
                    ".com/00000110240008_1/encoder/1/playlist.m3u8";
        }
        title = getIntent().getStringExtra("title");
        if (title == null || "".equals(title)) {
            title = "湖南卫视";
        }
        path = path.trim();
        LogUtils.i(title + "==" + path);
        videoView = (IjkVideoView) findViewById(R.id.videoview);
        lySystemParent = (LinearLayout) findViewById(R.id.ly_system_parent);
        flVideoView = (RelativeLayout) findViewById(R.id.fl_videoview);
        rlLoadView = (RelativeLayout) findViewById(R.id.rl_loading);
        tvLoadmsg = (TextView) findViewById(R.id.tv_load_msg);
        ivFullScreen = (ImageView) findViewById(R.id.iv_fullscreen);
        lyFloor = (LinearLayout) findViewById(R.id.ly_floor);

        tvTitle = (TextView) findViewById(R.id.tv_title);
        ivBack = (ImageView) findViewById(R.id.iv_back);
        ivMenu = (ImageView) findViewById(R.id.iv_menu);
        vClose = findViewById(R.id.v_close);

        channelList = (RecyclerView) this.findViewById(R.id.land_channel_list);
        channelList.setLayoutManager(new GridLayoutManager(this, 5));
        channelListAdapter = new LiveLandChannelAdapter(allLives,this);
        channelList.setAdapter(channelListAdapter);
        selectChannelBtn = this.findViewById(R.id.land_select_channel);
        selectChannelBtn.setOnClickListener(this);

        landBtnView = this.findViewById(R.id.land_btn_view);
        landLastBtn = this.findViewById(R.id.land_last_btn);
        landNextBtn = this.findViewById(R.id.land_next_btn);
        landLastBtn.setOnClickListener(this);
        landNextBtn.setOnClickListener(this);

        liveCollect = (CheckBox) this.findViewById(R.id.live_collect);
        liveCollect.setOnClickListener(this);

        indexChannel = (TextView) this.findViewById(R.id.live_channel_index);
        indexChannel.setText((index + 1) + "/" + ListUtils.getSize(allLives));
        lastChannel = (ImageView) this.findViewById(R.id.live_last_channel);
        nextChannel = (ImageView) this.findViewById(R.id.live_next_channel);
        lastChannel.setOnClickListener(this);
        nextChannel.setOnClickListener(this);
        radioGroup = (RadioGroup) this.findViewById(R.id.source_radio);
        radioGroup.setOnCheckedChangeListener(this);
        if (current_url.equals(url_1)) {
            radioGroup.check(R.id.source_1);
        } else if (current_url.equals(url_2)) {
            radioGroup.check(R.id.source_2);
        } else if (current_url.equals(url_3)) {
            radioGroup.check(R.id.source_3);
        }
        tvTitle.setText(title);
        tvLoadmsg.setText("视频加载中...");
        lySystemParent.setBackgroundColor(getResources().getColor(R.color.colorToolbar));
        ivFullScreen.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                fullChangeScreen();
            }
        });
        flVideoView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isShowToolbar) {
//                    setFullScreen();
                    isShowToolbar = false;
//                    getWindow().getDecorView().setSystemUiVisibility(View.GONE);
//                    ivFullScreen.setImageResource(R.drawable.bg_live_cancel_fullscreen_seletor);
                    hideToolbar(lySystemParent);
                    hideFloor(lyFloor);
                    channelList.setVisibility(View.INVISIBLE);
                } else {
//                    quitFullScreen();
                    isShowToolbar = true;
//                    getWindow().getDecorView().setSystemUiVisibility(View.VISIBLE);
//                    ivFullScreen.setImageResource(R.drawable.bg_live_cancel_fullscreen_seletor);
                    showToolbar(lySystemParent);
                    showFloor(lyFloor);
                }
            }
        });

        popupMenu = new LiveSizePopupMenu(this);
        popupMenu.setOnItemClickListener(new LiveSizePopupMenu.OnItemClickListener() {
            @Override
            public void onClick(int id) {
                switch (id) {
                    case R.id.tv_4_3:
                        setScreenRate(SIZE_4_3);
                        currentSize = SIZE_4_3;
                        break;
                    case R.id.tv_16_9:
                        setScreenRate(SIZE_16_9);
                        currentSize = SIZE_16_9;
                        break;
                    case R.id.tv_default:
                        setScreenRate(SIZE_DEFAULT);
                        currentSize = SIZE_DEFAULT;
                        break;
                }
            }
        });

        ivMenu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupMenu.showLocation(R.id.iv_menu);
            }
        });

        ivBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (getRequestedOrientation() == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE)// 横屏
                {
                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                    quitFullScreen();
                } else {
                    LivePlayActivity.this.finish();
                }
            }
        });


//        tvRelief.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                hideRelier(tvRelief);
//            }
//        });

        vClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                vClose.setVisibility(View.GONE);
            }
        });

        initVideo();
    }

    public void initVideo() {
        mSettings = new Settings(this);
        if (isScreenOriatationPortrait()) {
            screenWidth = ToolsUtil.getWidthInPx(this);
            screenHeight = ToolsUtil.getHeightInPx(this);
        } else {
            screenHeight = ToolsUtil.getWidthInPx(this);
            screenWidth = ToolsUtil.getHeightInPx(this);
        }

        // init player
        IjkMediaPlayer.loadLibrariesOnce(null);
        IjkMediaPlayer.native_profileBegin("libijkplayer.so");
        videoView.setVideoURI(Uri.parse(getPath(path.trim())));

        videoView.setOnPreparedListener(new IMediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(IMediaPlayer mp) {
                videoView.start();
                refreshChannelList();
            }
        });
        RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) flVideoView
                .getLayoutParams();
        lp.height = CommonUtil.getScreenWidth(this) * 3 / 4;
        lp.width = CommonUtil.getScreenWidth(this);
        flVideoView.setLayoutParams(lp);
        setScreenRate(2);

        videoView.setOnInfoListener(new IMediaPlayer.OnInfoListener() {
            @Override
            public boolean onInfo(IMediaPlayer mp, int what, int extra) {
                System.out.println("what:" + what);
                LogUtils.i("@@@@@@  " + "what: " + what);
                switch (what) {
                    case IjkMediaPlayer.MEDIA_INFO_BUFFERING_START:
                        LogUtils.i("@@@@@@  " + "START.......");
                        rlLoadView.setVisibility(View.VISIBLE);
//                        videoView.stopPlayback();
//                        initVideo();
                        break;
                    case IjkMediaPlayer.MEDIA_INFO_VIDEO_RENDERING_START:
                        LogUtils.i("@@@@@@  " + "RENDERING_START.......");
                        rlLoadView.setVisibility(View.GONE);
                        break;
                    case IjkMediaPlayer.MEDIA_INFO_BUFFERING_END:
                        LogUtils.i("@@@@@@  " + "END.......");
                        rlLoadView.setVisibility(View.GONE);
                        break;
                }
                return false;
            }
        });

        videoView.setOnCompletionListener(new IMediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(IMediaPlayer mp) {
                System.out.println("onCompletion");
                rlLoadView.setVisibility(View.VISIBLE);
                videoView.stopPlayback();
                videoView.release(true);
                videoView.setVideoURI(Uri.parse(getPath(path.trim())));
            }
        });

        videoView.setOnErrorListener(new IMediaPlayer.OnErrorListener() {
            @Override
            public boolean onError(IMediaPlayer mp, int what, int extra) {
                if (count > CONNECTION_TIMES) {
                    new AlertDialog.Builder(LivePlayActivity.this)
                            .setMessage("视频暂时不能播放")
                            .setPositiveButton(R.string.VideoView_error_button,
                                    new DialogInterface.OnClickListener() {
                                        public void onClick(DialogInterface dialog, int
                                                whichButton) {
                                            /* If we get here, there is no onError listener, so
                                             * at least inform them that the video is over.
                                             */
                                            LivePlayActivity.this.finish();
                                        }
                                    })
                            .setCancelable(false)
                            .show();
                } else {
                    videoView.stopPlayback();
                    videoView.release(true);
//                    videoView.stopBackgroundPlay();
//                    IjkMediaPlayer.native_profileEnd();
//
//                    IjkMediaPlayer.loadLibrariesOnce(null);
//                    IjkMediaPlayer.native_profileBegin("libijkplayer.so");


                    videoView.setVideoURI(Uri.parse(getPath(path.trim())));
                }
                System.out.println("replay------" + count++);
                return false;
            }
        });

    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    public void onBackPressed() {
        if (getRequestedOrientation() == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE)// 横屏
        {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
            quitFullScreen();
        } else {
            super.onBackPressed();
            mBackPressed = true;
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (mBackPressed || !videoView.isBackgroundPlayEnabled()) {
            videoView.stopPlayback();
            videoView.release(true);
            videoView.stopBackgroundPlay();
        }
        IjkMediaPlayer.native_profileEnd();
    }

    public static void activityStart(Context context, String url, String title) {
        Intent intent = new Intent(context, LivePlayActivity.class);
        intent.putExtra("url", url);
        intent.putExtra("title", title);
        context.startActivity(intent);
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {//竖屏
            RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) flVideoView
                    .getLayoutParams();
            lp.height = CommonUtil.getScreenHeight(this);
            lp.width = CommonUtil.getScreenWidth(this);
            flVideoView.setLayoutParams(lp);
            ivFullScreen.setImageResource(R.drawable.bg_live_cancel_fullscreen_seletor);
        } else {
            RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) flVideoView
                    .getLayoutParams();
            lp.height = CommonUtil.getScreenWidth(this) * 3 / 4;
            lp.width = CommonUtil.getScreenWidth(this);
            flVideoView.setLayoutParams(lp);
            ivFullScreen.setImageResource(R.drawable.bg_live_fullscreen_seletor);
        }
        setScreenRate(currentSize);
    }

    public void fullChangeScreen() {
        if (getRequestedOrientation() == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE)// 切换为竖屏
        {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
            quitFullScreen();
        } else {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
            setFullScreen();
        }
    }

    public void setScreenRate(int rate) {
        int width = 0;
        int height = 0;
        if (getRequestedOrientation() == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE)// 横屏
        {
            if (rate == SIZE_DEFAULT) {
                width = videoView.getmVideoWidth();
                height = videoView.getmVideoHeight();
            } else if (rate == SIZE_4_3) {
                width = screenWidth / 3 * 4;
                height = screenWidth;
            } else if (rate == SIZE_16_9) {
                width = screenWidth / 9 * 16;
                height = screenWidth;
            }
        } else //竖屏
        {
            if (rate == SIZE_DEFAULT) {
                width = videoView.getmVideoWidth();
                height = videoView.getmVideoHeight();
            } else if (rate == SIZE_4_3) {
                width = screenWidth;
                height = screenWidth * 3 / 4;
            } else if (rate == SIZE_16_9) {
                width = screenWidth;
                height = screenWidth * 9 / 16;
            }
        }
        if (width > 0 && height > 0) {
            FrameLayout.LayoutParams lp = (FrameLayout.LayoutParams) videoView.getmRenderView()
                    .getView().getLayoutParams();
            lp.width = width;
            lp.height = height;
            videoView.getmRenderView().getView().setLayoutParams(lp);
        }
    }

    public void hideToolbar(final View v) {
        ValueAnimator animator;
        animator = ValueAnimator.ofFloat(0, -(CommonUtil.dip2px(this, 55) + CommonUtil
                .getStatusHeight(this)));
        animator.setTarget(v);
        animator.setDuration(400).start();
        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                v.setTranslationY((Float) animation.getAnimatedValue());
            }
        });
    }

    public void showToolbar(final View v) {
        ValueAnimator animator;
        if (Build.VERSION.SDK_INT >= 19) {
            animator = ValueAnimator.ofFloat(-(CommonUtil.dip2px(this, 55) + CommonUtil
                    .getStatusHeight(this)), 0);
        } else {
            animator = ValueAnimator.ofFloat(-CommonUtil.dip2px(this, 55), 0);
        }
        animator.setTarget(v);
        animator.setDuration(500).start();
        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                v.setTranslationY((Float) animation.getAnimatedValue());
            }
        });
    }

    public void hideFloor(final View v) {
        ValueAnimator animator;
        if (Build.VERSION.SDK_INT >= 19) {
            animator = ValueAnimator.ofFloat(0, (CommonUtil.dip2px(this, 55) + CommonUtil
                    .getStatusHeight(this)));
        } else {
            animator = ValueAnimator.ofFloat(0, CommonUtil.dip2px(this, 55));
        }

        animator.setTarget(v);
        animator.setDuration(400).start();
        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                v.setTranslationY((Float) animation.getAnimatedValue());
            }
        });
    }

    public void showFloor(final View v) {
        ValueAnimator animator;
        animator = ValueAnimator.ofFloat(CommonUtil.dip2px(this, 55), 0);
        animator.setTarget(v);
        animator.setDuration(400).start();
        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                v.setTranslationY((Float) animation.getAnimatedValue());
            }
        });
    }

    public void showRelier(final View v) {
        ValueAnimator animator;
        animator = ValueAnimator.ofFloat(0, -CommonUtil.dip2px(this, 172));
        animator.setTarget(v);
        animator.setDuration(400).start();
        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                v.setTranslationY((Float) animation.getAnimatedValue());
            }
        });
        vClose.setVisibility(View.VISIBLE);
    }

    public void hideRelier(final View v) {
        ValueAnimator animator;
        animator = ValueAnimator.ofFloat(-CommonUtil.dip2px(this, 172), 0);
        animator.setTarget(v);
        animator.setDuration(400).start();
        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                v.setTranslationY((Float) animation.getAnimatedValue());
            }
        });

    }

    public boolean isScreenOriatationPortrait() {
        return this.getResources().getConfiguration().orientation == Configuration
                .ORIENTATION_PORTRAIT;
    }


    private void quitFullScreen() {
        final WindowManager.LayoutParams attrs = getWindow().getAttributes();
        attrs.flags &= (~WindowManager.LayoutParams.FLAG_FULLSCREEN);
        getWindow().setAttributes(attrs);
        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
        landBtnView.setVisibility(View.INVISIBLE);
        channelList.setVisibility(View.INVISIBLE);
    }


    private void setFullScreen() {
        landBtnView.setVisibility(View.VISIBLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
    }

    private void lastLive() {
        if (ListUtils.getSize(allLives) > index) {
            videoView.release(true);
            index--;
            if (index == -1) {
                index = allLives.size() - 1;
            }
            path = allLives.get(index).getPath();
            tvTitle.setText(allLives.get(index).getTitle());
            videoView.setVideoURI(Uri.parse(getPath(path.trim())));
            videoView.start();
            refreshChannelList();
            indexChannel.setText((index + 1) + "/" + ListUtils.getSize(allLives));
        }
    }

    private void nextLive() {
        if (ListUtils.getSize(allLives) > index) {
            videoView.release(true);
            index++;
            if (index == allLives.size() - 1) {
                index = 0;
            }
            path = allLives.get(index).getPath();
            tvTitle.setText(allLives.get(index).getTitle());
            videoView.setVideoURI(Uri.parse(getPath(path.trim())));
            videoView.start();
            refreshChannelList();
            indexChannel.setText((index + 1) + "/" + ListUtils.getSize(allLives));
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.land_last_btn:
            case R.id.live_last_channel:
                lastLive();
                break;
            case R.id.land_next_btn:
            case R.id.live_next_channel:
                nextLive();
                break;
            case R.id.live_collect:
                Live live = new Live();
                live.setLiveName(title);
                live.setLivePath(path);
                if (liveCollect.isChecked()) {
                    dao.insert(live);
                } else {
                    dao.delete(live);
                }
                break;
            case R.id.land_select_channel:
                if (channelList.getVisibility() == View.INVISIBLE) {
                    channelList.setVisibility(View.VISIBLE);
                } else {
                    channelList.setVisibility(View.INVISIBLE);
                }
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        allLives = null;
        index = 0;
    }

    private String getPath(String path) {
        if (path.contains("live.aishang.ctlcdn.com")) {
            path = current_url + path;
        }
        LogUtils.i("######### path: " + path);
        return path;
    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        switch (checkedId) {
            case R.id.source_1:
                current_url = url_1;
                break;
            case R.id.source_2:
                current_url = url_2;
                break;
            case R.id.source_3:
                current_url = url_3;
                break;
        }
        LogUtils.d("######: " + current_url);
        videoView.release(true);
        videoView.setVideoURI(Uri.parse(getPath(path.trim())));
        videoView.start();
        refreshChannelList();
    }

    @Override
    public void onChannelItemClick(int index) {
        this.index = index;
        path = allLives.get(index).getPath();
        tvTitle.setText(allLives.get(index).getTitle());
        videoView.setVideoURI(Uri.parse(getPath(path.trim())));
        videoView.start();
        refreshChannelList();
        indexChannel.setText((index + 1) + "/" + ListUtils.getSize(allLives));
//        channelList.setVisibility(View.INVISIBLE);
    }

    private void refreshChannelList() {
        channelListAdapter.setCurrentIndex(index);
        channelListAdapter.notifyDataSetChanged();
    }
}
